package djboom.materials.display.page {
	import djboom.materials.Work;
	import djboom.materials.core.BitmapDataCore;
	import djboom.materials.core.DataCore;
	import djboom.materials.display.elements.RoundedButton;
	import djboom.materials.events.PageEvent;
	import djboom.materials.state.Font;

	import org.casalib.display.CasaBitmap;
	import org.casalib.display.CasaShape;
	import org.casalib.display.CasaTextField;
	import org.casalib.util.NumberUtil;

	import flash.display.CapsStyle;
	import flash.display.JointStyle;
	import flash.display.LineScaleMode;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.text.AntiAliasType;
	import flash.text.StyleSheet;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.ui.Keyboard;

	/**
	 * .
	 * <br>
	 * 
	 * @author DJ BooM 
	 * @since 06.04.2010
	 * 
	 */

	public class Conclusion extends Page {

		// ----------------------------------------------------------------------------
		// Константы класса.
		// ----------------------------------------------------------------------------

		public static const EQUATION:String = "conclusion.Equation";

		// ----------------------------------------------------------------------------
		// Свойства класса.
		// ----------------------------------------------------------------------------

		private var _textField:CasaTextField;
		private var _trueDensityField:CasaTextField;
		private var _averageDensityField:CasaTextField;
		private var _equationBitmap:CasaBitmap;
		private var _cellField:CasaTextField;
		private var _shapeCell:CasaShape;
		private var _strokeCell:CasaShape;
		private var _porosity:Number;
		private var _simpleButton:RoundedButton;

		// ----------------------------------------------------------------------------
		// Конструктор.
		// ----------------------------------------------------------------------------

		public function Conclusion() {
			super();
		}	 

		// ----------------------------------------------------------------------------
		// Методы класса.
		// ----------------------------------------------------------------------------

		private function changePage(event:MouseEvent):void {
			var pageEvent:PageEvent = new PageEvent(PageEvent.CHANGE);
			pageEvent.pageName = Page.THANKS_PAGE;            
			dispatchEvent(pageEvent);
		}

		// ----------------------------------------------------------------------------
		// Публичные методы.
		// ----------------------------------------------------------------------------

		override public function init():void {
			// Создаем заголовок страницы.
			createTitlePage("Заключение");
			
			var materialsList:XMLList = DataCore._materialsWork3XML.child("material").(@select == "true");
			var nameMaterial:String = XML(materialsList[0]).attribute("name").toString();
			var trueDenSityKG:String = XML(materialsList[0]).attribute("trueDenSityKG").toString();

			var materialaverage_kg:String = XML(materialsList[0]).attribute("averageHardness_KG").toString();
			
			switch(nameMaterial) {
				case "Тяжелый бетон":
					nameMaterial = "тяжелого бетона";
					break;
                    
				case "Керамзитобетон":
					nameMaterial = "керамзитобетона";
					break;
                    
				case "Ячеистый бетон":
					nameMaterial = "ячеистого бетона";
					break;
                    
				case "Кирпич керамический полнотелый":
					nameMaterial = "кирпича керамического полнотелого";
					break;
                    
				case "Кирпич керамический пустотелый":
					nameMaterial = "кирпича керамического пустотелого";
					break;
                    
				case "Кирпич силикатный":
					nameMaterial = "кирпича силикатного";
					break;
				
				case "Вулканический туф":
					nameMaterial = "вулканического туфа";
					break;
                    
				case "Гранит":
					nameMaterial = "гранита";
					break;
				
				case "Известняк":
					nameMaterial = "известняка";
					break;
			}
			
            
			var style:StyleSheet = new StyleSheet();
			style.setStyle("p", {fontFamily: "Myriad Pro Cond", fontSize: "26", color: "#004064", fontStyle: "italic"});
			style.setStyle(".specialSymbols", {fontFamily: Font.SPECIAL, fontSize: "18"});
            
			_textField = new CasaTextField();
			_textField.styleSheet = style;
			_textField.embedFonts = true;
			_textField.selectable = false;
			_textField.multiline = true;
			_textField.wordWrap = true;
			_textField.autoSize = TextFieldAutoSize.LEFT;            
			_textField.antiAliasType = AntiAliasType.ADVANCED;
			_textField.htmlText = "<p>Сопоставьте результаты определения средней и истинной плотности " + nameMaterial + " и рассчитайте его пористость.</p>";
			_textField.thickness = 40;
			_textField.width = 950;			
			_textField.x = 40;
			_textField.y = 100;
			addChild(_textField);
			
			_trueDensityField = new CasaTextField();
			_trueDensityField.styleSheet = style;
			_trueDensityField.embedFonts = true;
			_trueDensityField.selectable = false;
			_trueDensityField.autoSize = TextFieldAutoSize.LEFT;            
			_trueDensityField.antiAliasType = AntiAliasType.ADVANCED;
			_trueDensityField.htmlText = '<p>Истинная плотность:   <b>' + trueDenSityKG + ' кг/м <span class="specialSymbols">3</span></b></p>';
			_trueDensityField.thickness = 40;
			_trueDensityField.x = 40;
			_trueDensityField.y = 190;
			addChild(_trueDensityField);
            
			_averageDensityField = new CasaTextField();
			_averageDensityField.styleSheet = style;
			_averageDensityField.embedFonts = true;
			_averageDensityField.selectable = false;
			_averageDensityField.autoSize = TextFieldAutoSize.LEFT;            
			_averageDensityField.antiAliasType = AntiAliasType.ADVANCED;
			_averageDensityField.htmlText = '<p>Средняя плотность:   <b>' + materialaverage_kg + ' кг/м <span class="specialSymbols">3</span></b></p>';
			_averageDensityField.thickness = 40;
			_averageDensityField.x = 40;
			_averageDensityField.y = 230;
			addChild(_averageDensityField);
            
			_equationBitmap = new CasaBitmap(BitmapDataCore.getBitmapData(EQUATION));
			_equationBitmap.x = 260;			_equationBitmap.y = 360;
			addChild(_equationBitmap);
            
			_porosity = NumberUtil.roundDecimalToPlace((((Number(trueDenSityKG) - Number(materialaverage_kg)) / Number(trueDenSityKG)) * 100), 1);
            
			_shapeCell = new CasaShape();
			_shapeCell.graphics.beginFill(0xca1235);
			_shapeCell.graphics.drawRect(0, 0, 90, 56);
			_shapeCell.graphics.endFill();
			_shapeCell.alpha = 0.1; 
			_shapeCell.x = 600;			_shapeCell.y = 360;
			addChild(_shapeCell);
            
			var cellTF:TextFormat = new TextFormat(Font.MYRIAD_PRO_COND, 36, 0xca1235, true, true);
            
			_cellField = new CasaTextField();
			_cellField.embedFonts = true;
			_cellField.defaultTextFormat = cellTF;
			_cellField.width = 90;
			_cellField.autoSize = TextFieldAutoSize.CENTER;
			_cellField.antiAliasType = AntiAliasType.ADVANCED;
			_cellField.thickness = 50;
			_cellField.tabEnabled = false;
			_cellField.x = 648;
			_cellField.y = 365;
			addChild(_cellField);
            
			_cellField.text = "";
            
			_strokeCell = new CasaShape();
			_strokeCell.graphics.lineStyle(4, 0xca1235, 1, false, LineScaleMode.VERTICAL, CapsStyle.SQUARE, JointStyle.MITER);
			_strokeCell.graphics.drawRect(0, 0, 90, 56);
			_strokeCell.x = 600;
			_strokeCell.y = 360;
			addChild(_strokeCell);
            
            
			_cellField.selectable = true;
			_cellField.mouseEnabled = true;
			_cellField.type = TextFieldType.INPUT;
            
			_cellField.maxChars = 4;
			_cellField.restrict = "0-9,.";
            
			stage.focus = _cellField;
            
			_cellField.addEventListener(KeyboardEvent.KEY_DOWN, checkDataKey);
			_cellField.addEventListener(FocusEvent.FOCUS_OUT, checkDataFocus);
		}

		private function checkDataFocus(event:FocusEvent):void {
			stage.focus = _cellField;
		}

		private function checkDataKey(event:KeyboardEvent):void {
			if (event.keyCode == Keyboard.ENTER || event.keyCode == Keyboard.RIGHT) {
				checkInputData();
			}
		}

		private function checkInputData():void {
			if (_cellField.text.indexOf(",") != -1) {
				var i:Array = _cellField.text.split(",");
				_cellField.text = new String().concat(i[0], ".", i[1]);
			}
            
			if (_cellField.text == String(_porosity)) {
				_cellField.text = _porosity + " %";
				disableInput();
				
				_simpleButton = new RoundedButton("Продолжить");
				_simpleButton.x = Work.WIDTH * 0.5 - _simpleButton.width * 0.5;
				_simpleButton.y = Work.HEIGHT - 118;
				_simpleButton.addEventListener(MouseEvent.CLICK, changePage);
				addChild(_simpleButton);
			} else {
				_cellField.text = "";
			}
		}

		private function disableInput():void {
			if (_cellField != null) {
				_cellField.selectable = false;
				_cellField.mouseEnabled = false;
				_cellField.type = TextFieldType.DYNAMIC;
            
				_cellField.removeEventListener(KeyboardEvent.KEY_DOWN, checkDataKey);
				_cellField.removeEventListener(FocusEvent.FOCUS_OUT, checkDataFocus);
			}
            
			if (_shapeCell != null) {
				_shapeCell.alpha = 0;
			}
            
			if (_strokeCell != null) {
				_strokeCell.destroy();
				_strokeCell = null;
			}
		}

		override protected function clearPage(event:Event):void {
			super.clearPage(event);
		}
        
		// ----------------------------------------------------------------------------
        // Публичные свойства.
        // ----------------------------------------------------------------------------
	}
}
